package com.util.tool;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

public class HttpHelper {
	private static URL urls;
	private static ByteArrayOutputStream bos;
	private static InputStream in;
	private static OutputStream out;

	/**
	 * @param url
	 * @return
	 */
	public static InputStream loadFileFromURLByURL(String url) {
		try {
			urls = new URL(url);
			return urls.openStream();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 将输入流内容读取
	 * 
	 * @param in
	 * @return
	 */
	public static byte[] loadByteFromURL(String url) {
		in = loadFileFromURLByURL(url);
		bos = new ByteArrayOutputStream();
		if (in != null) {
			byte b[] = new byte[1024 * 4];
			int len;
			try {
				while ((len = in.read(b)) != -1) {
					bos.write(b, 0, len);
					bos.flush();
				}
				return bos.toByteArray();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				doClose();
			}
		}
		return null;
	}

	public static String loadStringFromUrl(String url) {
		return new String(loadByteFromURL(url));
	}

	private static void doClose() {
		if (bos != null)
			try {
				bos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		if (in != null)
			try {
				in.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		if (out != null)
			try {
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
}
